<template>
  <!-- 组织架构 -->
  <div class="app-container">

    <div class="left"> <!-- 树形组件 -->
      <!-- <el-button type="primary">主要按钮</el-button> -->
      <el-tree ref="deptTree" :data="depts" :props="defaultProps" :default-expand-all="true" :highlight-current="false"
        :expand-on-click-node="false" node-key="id" @node-click="selectNode"></el-tree>
    </div>
    <div class="right">

      <div class="navbar">
        <!-- 面包屑展示 -->
        <div class="navbar-item biaoqian-box" v-if="departmentName">
          <span>{{ departmentName }}</span>
          <button class=" close-button" @click="removeTab"></button>
        </div>
        <!-- 搜索框展示 -->
        <el-input class="navbar-item search-box" type="text" prefix-icon="el-icon-search" size="small"
          v-model="queryParams.keyword" @keyup.enter.native="selectKeywordDebounce" placeholder="输入员工姓名全员搜索" />

        <div class=" navbar-item">
          <el-row type="flex" justify="end">
            <el-button size="mini" type="primary" @click="addUser" v-permission="'01001'">添加员工</el-button>
          </el-row>
        </div>
      </div>
      <div class="right-table">


        <el-table :data="userList" style="width: 100%;" @selection-change="handleSelectionChange"
          :row-class-name="tableRowClassName" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column v-if="columnVisibility.username" fixed prop="user_name" label="用户名" align="center"
            width="120">
          </el-table-column>
          <el-table-column prop="nick_name" label="名称" align="center" width="120">
          </el-table-column>
          <el-table-column prop="avatar" align="center" label="头像" width="120">
            <template v-slot="{ row }">
              <el-avatar v-if="row.avatar" :src="row.avatar" :size="30" />
              <span v-else class="username"> {{ row.user_name?.charAt(0) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" align="center" width="120">
          </el-table-column>
          <el-table-column prop="phone" label="手机号" align="center" width="120">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" align="center" width="120">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.role_name" placement="top">
                <div class="role-name-cell">{{ scope.row.role_name }}</div>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="assigningRole(scope.row)"
                v-permission="'01004'">分配角色</el-button>
              <el-button type="text" size="small" @click="editUser(scope.row)" v-permission="'01002'">编辑</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="delUser(scope.row)">
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px"
                  v-permission="'01003'">删除</el-button>
              </el-popconfirm>
              <!-- <el-button @click="delUser(scope.row)" type="text" size="small">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination @size-change="changePageSize" @current-change="changePageIndex"
        :current-page="queryParams.pageIndex" :page-sizes="[1, 10, 20, 50]" :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="userTotal">
      </el-pagination>

      <!-- 增删页面弹层 -->
      <organization-add ref="addUser" :show-dialog.sync="showDialog" :title="dialogTitle" :userId="userId"
        @submit="getUserList"></organization-add>

      <user-role ref="userRole" :show-role-dialog.sync="showRoleDialog" :title="roleDialogTitle" :userId="userId"
        @submit="getUserList"></user-role>
    </div>
  </div>



</template>
<script>
import { getDepartmentList } from '@/api/department';
import { getUserList, delUser } from '@/api/user';
import { transListToTreeData } from '@/utils'
import organizationAdd from './organizationAdd.vue';
import userRole from './userRole.vue';
import { debounce } from 'lodash';
export default {
  name: 'organization',
  components: { organizationAdd, userRole },
  data() {
    return {

      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      userList: [],
      //批量选中
      selectedRows: [],
      // 用户总记录数
      userTotal: 0,
      departmentName: null,
      // 新增修改弹层
      showDialog: false,
      showRoleDialog: false,
      dialogTitle: '新增用户',
      roleDialogTitle: '新增用户',
      userId: null,
      // 查询参数
      queryParams: {
        departmentId: null,
        pageIndex: 0,
        pageSize: 10,
        keyword: ''
      },
      // 列显示状态
      columnVisibility: {
        username: true,
        nickname: true,
        avatar: true,
        email: true,
        phone: true,
        operation: true
      },
    }
  },
  created() {
    //访问后端部门接口
    this.getDepartmentList()
    // 初始化防抖函数
    this.selectKeywordDebounce = debounce(this.selectKeyword, 1000); // 1秒防抖

  },
  methods: {
    async getDepartmentList() {
      let result = await getDepartmentList()
      // 递归处理
      this.depts = transListToTreeData(result, 0)

      this.$nextTick(() => {
        if (this.$refs.deptTree) {
          this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
        }


      })
      this.getUserList()
    },
    selectNode(node) {
      this.departmentName = node.name

      this.queryParams.departmentId = node.id
      this.getUserList()
    },
    async getUserList() {
      const { data, total } = await getUserList(this.queryParams)

      this.userList = data
      this.userTotal = total

    },

    changePageIndex(newPageIndex) {
      //切换页数
      this.queryParams.pageIndex = newPageIndex - 1
      this.getUserList()
    },
    changePageSize(newPageSize) {
      //切换条数
      this.queryParams.pageSize = newPageSize
      //切换条数 页数默认置0
      this.queryParams.pageIndex = 0
      this.getUserList()
    },
    // 搜索功能
    selectKeyword() {
      this.queryParams.pageIndex = 0
      this.getUserList()
    },
    removeTab() {
      this.queryParams.departmentId = null
      this.departmentName = null;
      this.getUserList()
    },
    //新增用户
    addUser() {
      this.userId = null
      this.showDialog = true
      this.dialogTitle = '新增用户'
    },
    //编辑用户
    editUser(row) {
      this.userId = row.id
      this.showDialog = true
      this.dialogTitle = '编辑用户'

      // this.$nextTick(() => {
      //   this.$refs.addUser.getuserDetail()
      // })

    },
    //分配用户角色
    assigningRole(row) {

      this.userId = row.id
      this.showRoleDialog = true
      this.roleDialogTitle = `分配角色权限：${row.user_name}`
      this.$nextTick(() => {
        this.$refs.userRole.getUserRole()
      })

    },
    async delUser(row) {

      console.log('delete');

      await delUser({ id: row.id })
      // 提示消息
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 监听表格选中变化
    handleSelectionChange(selection) {
      this.selectedRows = selection.map(row => row.id);
      console.log('当前选中的行id：', this.selectedRows);
      // this.selectedRows = selection; // 更新选中的行数据
    },
    tableRowClassName({ row, rowIndex }) {
      // 判断是否是偶数行（索引从 0 开始）
      if (rowIndex % 2 === 1) {
        return 'even-row'; // 偶数行的类名
      }
      return ''; // 其他行不添加类名
    },
    // 搜索功能
    selectKeyword() {
      this.queryParams.pageIndex = 0
      this.getUserList()
    },
  }
}
</script>

<style scoped>
.app-container {
  background: #fff;
  display: flex;
  border-radius: 5px;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
    overflow-y: auto;
  }

  .right {
    flex: 1;
    padding: 20px;

    .navbar {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 20px;

      /* 设置间距 */
      .navbar-item {
        display: inline-block;
        white-space: nowrap;

      }

      .biaoqian-box {
        width: 100px;
        /* 设置宽度 */
        height: 30px;
        /* 设置高度 */
        border: 1px solid #ccc;
        line-height: 30px;
        border-radius: 4px;
        cursor: pointer;
        text-align: center;
        /* 确保输入框内容垂直居中 */
        font-size: 12px;
        position: relative;
        /* 添加相对定位，为子元素的绝对定位提供参考 */
        padding-right: 20px;
        /* 给关闭按钮留出空间 */

        /* 调整字体大小以适应高度 */
        .close-button {
          background: none;
          border: none;
          padding: 0;
          cursor: pointer;
          position: absolute;
          /* 使用绝对定位 */
          right: 5px;
          /* 距离右侧 5px */
          top: 50%;
          /* 垂直居中 */
          transform: translateY(-50%);
          /* 微调垂直位置 */
        }

        .close-button::before {
          content: "×";
          text-align: center;
          font-size: 16px;
          color: #999;
        }
      }

      .search-box {
        width: 280px;
        /* 设置宽度 */
        height: 20px;
        /* 设置高度 */
        line-height: 20px;
        margin-bottom: 10px;
        /* 确保输入框内容垂直居中 */
        font-size: 12px;
        /* 调整字体大小以适应高度 */
      }

    }


    .right-table {
      overflow-x: scroll;

      .role-name-cell {
        white-space: nowrap;
        /* 防止换行 */
        overflow: hidden;
        /* 隐藏超出部分 */
        text-overflow: ellipsis;
        /* 显示省略号 */
        max-width: 120px;
        /* 设置最大宽度与列宽一致 */
      }
    }

    ::v-deep(.el-table .even-row) {
      background-color: #f8f8f9;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>